import groovy.jmx.builder.JmxBuilder
import javax.management.MBeanServer
import javax.management.ObjectName

class JmxMBeanExportFactoryTest extends GroovyTestCase {
    def jmx

    void testInitializtion() {
        jmx = new JmxBuilder()
        assertTrue jmx != null
    }

    void setUp() {
        jmx = new JmxBuilder()
    }

    void testJmxMBeanExportFactorySansServer() {
        def parent = jmx.export()
        assert parent
        assert parent instanceof MBeanServer
    }

    void testJmxMBeanExportFactory() {
        def parent = jmx.export(javax.management.MBeanServerFactory.createMBeanServer())
        assert parent
        assert parent instanceof MBeanServer
    }

    void testJmxMBeanFactoryExportExplicit() {
        def observed = new ExposedTestBean()
        MBeanServer parent = jmx.export {
            bean(observed) {
                name("jmxBuilder:type=bean")
                description("This is a test bean")
                operation('name': "toss", 'desc': "toss operation") {
                    parameter('type': 'int', 'name': "distance", 'desc': "distance for toss")
                    parameter('type': 'java.lang.Object', 'name': "force", 'desc': "force to use")
                }
                operation('name': "stretch", 'desc': "This operation stretches object")
                constructor("name": "Constructor2") {
                    parameter(type: "int", 'name': "size", 'desc': "size")
                    parameter(type: "int", 'name': "length", 'desc': "length")
                }
            }
            bean(object: new TestJavaBean(), name: 'jmxBuilder:type=bean2')
        }

        assert parent
        assert parent.isRegistered(new ObjectName("jmxBuilder:type=bean"))
        assert parent.getMBeanInfo(new ObjectName("jmxBuilder:type=bean")).getDescriptor().getFieldValue("displayName") == "This is a test bean"
        assert parent.isRegistered(new ObjectName("jmxBuilder:type=bean2"))

        parent.unregisterMBean new ObjectName("jmxBuilder:type=bean")
        parent.unregisterMBean new ObjectName("jmxBuilder:type=bean2")
    }

}